package com.rykj.qxj.server.services.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.rykj.qxj.server.common.constants.ApiRequestModeStatusEnum;
import com.rykj.qxj.server.common.constants.ApiStatusEnum;
import com.rykj.qxj.server.common.constants.ApiVerifyStatusEnum;
import com.rykj.qxj.server.common.constants.ChangeTypeEnum;
import com.rykj.qxj.server.common.constants.CreateMethodEnum;
import com.rykj.qxj.server.common.constants.DeleteStatusEnum;
import com.rykj.qxj.server.common.constants.YesOrNoStatusEnum;
import com.rykj.qxj.server.common.exception.AddFieldDuplicatePenNameException;
import com.rykj.qxj.server.common.exception.AddFieldListIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.ApiManageIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.ApiManageSaveExceptiuon;
import com.rykj.qxj.server.common.exception.ApiOfTableListIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.ApiOfTableOfFieldIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.ApiOfTableSaveExceptiuon;
import com.rykj.qxj.server.common.exception.ApiRequestParamDuplicateBySqlException;
import com.rykj.qxj.server.common.exception.ApiRequestParamDuplicatePenNameException;
import com.rykj.qxj.server.common.exception.ApiRequestParamListIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.ApiResponseParamDuplicateBySqlException;
import com.rykj.qxj.server.common.exception.ApiResponseParamDuplicatePenNameException;
import com.rykj.qxj.server.common.exception.ApiResponseParamListIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.ApiStatusDisableExceptiuon;
import com.rykj.qxj.server.common.exception.ApiVersionManageIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.ApiVersionManageaveExceptiuon;
import com.rykj.qxj.server.common.exception.ApiVersionStatusDisableExceptiuon;
import com.rykj.qxj.server.common.exception.ApplyIdIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.FileApiCatalogListIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.FileApiNameListIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.NameByUrlIsDupExceptiuon;
import com.rykj.qxj.server.common.exception.NameByUrlIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.RequestParamAndUpdateFieldDuplicatePenNameExceptiuon;
import com.rykj.qxj.server.common.exception.SqlTempletIsNullExceptiuon;
import com.rykj.qxj.server.common.exception.UpdateFieldDuplicatePenNameException;
import com.rykj.qxj.server.common.exception.UpdateFieldListIsNullExceptiuon;
import com.rykj.qxj.server.common.utils.CollectionUtils;
import com.rykj.qxj.server.common.utils.StringUtils;
import com.rykj.qxj.server.dao.AddFieldMapper;
import com.rykj.qxj.server.dao.ApiManageMapper;
import com.rykj.qxj.server.dao.ApiOfTableMapper;
import com.rykj.qxj.server.dao.ApiOfTableOfFieldMapper;
import com.rykj.qxj.server.dao.ApiRequestParamMapper;
import com.rykj.qxj.server.dao.ApiResponseParamMapper;
import com.rykj.qxj.server.dao.ApiVersionManageMapper;
import com.rykj.qxj.server.dao.ApplyManageMapper;
import com.rykj.qxj.server.dao.FileApiCatalogMapper;
import com.rykj.qxj.server.dao.FileApiNameMapper;
import com.rykj.qxj.server.dao.MetadataBasicMapper;
import com.rykj.qxj.server.dao.UpdateFieldMapper;
import com.rykj.qxj.server.model.entity.AddField;
import com.rykj.qxj.server.model.entity.ApiManage;
import com.rykj.qxj.server.model.entity.ApiOfTable;
import com.rykj.qxj.server.model.entity.ApiOfTableOfField;
import com.rykj.qxj.server.model.entity.ApiRequestParam;
import com.rykj.qxj.server.model.entity.ApiResponseParam;
import com.rykj.qxj.server.model.entity.ApiVersionManage;
import com.rykj.qxj.server.model.entity.Apply;
import com.rykj.qxj.server.model.entity.ApplyApi;
import com.rykj.qxj.server.model.entity.FileApiCatalog;
import com.rykj.qxj.server.model.entity.FileApiName;
import com.rykj.qxj.server.model.entity.MetadataBasic;
import com.rykj.qxj.server.model.entity.UpdateField;
import com.rykj.qxj.server.model.param.ApiManagerOutsideUrlParams;
import com.rykj.qxj.server.model.param.ApiManagerParams;
import com.rykj.qxj.server.services.IApiManageService;
import com.techindata.cacheredis.CacheCom;
import com.techindata.cacheredis.CacheExsite;
import com.techindata.cacheredis.CacheZSet;

import lombok.extern.log4j.Log4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;

import javax.annotation.Resource;


@Log4j
@Service
public class ApiManageServiceImpl implements IApiManageService {

	@Resource
	private ApiManageMapper apiManageMapper;

	@Resource
	private ApiVersionManageMapper apiVersionManageMapper;
	
	@Resource
	private ApiOfTableMapper apiOfTableMapper;
	
	@Resource
	private ApiOfTableOfFieldMapper apiOfTableOfFieldMapper;
	
	@Resource
	private ApiRequestParamMapper apiRequestParamMapper;
	
	@Resource
	private ApiResponseParamMapper apiResponseParamMapper;
	
	@Resource
	private MetadataBasicMapper metadataBasicMapper;
	
	@Resource
	private UpdateFieldMapper updateFieldMapper;
	@Autowired
	private AddFieldMapper addFieldMapper;
	
	@Autowired
	private ApplyManageMapper applyManageMapper;
	@Autowired
	private FileApiCatalogMapper fileApiCatalogMapper;
	@Autowired
	private FileApiNameMapper fileApiNameMapper;
	
	private static final String requestMethodGet = "GET";
	private static final String requestMethodPost = "POST";
	private static final String requestMethodPut = "PUT";
	private static final String requestMethodDelete = "DELETE";
	private static final String PER_API_VISITCOUNT= "perApiVisitCount";
	
	private static final String BUSINESS="business";
	
	private static final String API_PREFIX="/data-api";
	
	@Transactional(rollbackFor=Exception.class)
	public void saveApiManage(ApiManagerParams apiManagerParams) 
			throws ApiManageSaveExceptiuon, ApiVersionManageIsNullExceptiuon, 
			ApiOfTableListIsNullExceptiuon, ApiOfTableOfFieldIsNullExceptiuon,
			ApiOfTableSaveExceptiuon, ApiRequestParamListIsNullExceptiuon, 
			ApiResponseParamListIsNullExceptiuon, ApiManageIsNullExceptiuon, ApiVersionManageaveExceptiuon, UpdateFieldListIsNullExceptiuon, AddFieldListIsNullExceptiuon, ApplyIdIsNullExceptiuon, ApiRequestParamDuplicatePenNameException, ApiResponseParamDuplicatePenNameException, UpdateFieldDuplicatePenNameException, AddFieldDuplicatePenNameException, RequestParamAndUpdateFieldDuplicatePenNameExceptiuon, JSQLParserException, SqlTempletIsNullExceptiuon, ApiRequestParamDuplicateBySqlException, ApiResponseParamDuplicateBySqlException {
		final String versionNumber="v1.00";
		ApiManage apiManage = apiManagerParams.getApiManage();
		List<ApiOfTable> apiOfTableList = apiManagerParams.getApiOfTableList();
		List<ApiOfTableOfField> apiOfTableOfFieldList = apiManagerParams.getApiOfTableOfFieldList();
		List<ApiRequestParam> apiRequestParamList = apiManagerParams.getApiRequestParamList();
		List<ApiResponseParam> apiResponseParamList = apiManagerParams.getApiResponseParamList();
		ApiVersionManage apiVersionManage = apiManagerParams.getApiVersionManage();
		List<UpdateField> updateFieldList = apiManagerParams.getUpdateFieldList();
		List<AddField> addFieldList = apiManagerParams.getAddFieldList();
		//List<FileApiCatalog> fileApiCatalogList = apiManagerParams.getFileApiCatalogList();
		//List<FileApiName> fileApiNameList = apiManagerParams.getFileApiNameList();
		if(apiManage==null) {
			throw new ApiManageIsNullExceptiuon("接口基本信息不能为空");
		}
		apiManage.setCreateTime(new Date());
		apiManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
		apiManage.setApiStatus(ApiStatusEnum.ENABLE.getStatus());
		apiManage.setUrl(API_PREFIX+apiManage.getUrl());
		apiManage.setIsOutSide(YesOrNoStatusEnum.NO.getStatus());
		apiManageMapper.saveApiManage(apiManage);
		if(log.isInfoEnabled()) {
			log.info("apiManage save success after id="+apiManage.getId());
		}
		//保存成功以后返回接口的Id
		if(apiManage.getId()==null) {
			throw new ApiManageSaveExceptiuon("接口基本信息保存异常");
			
		}
		if(apiVersionManage==null) {
			throw new ApiVersionManageIsNullExceptiuon("接口版本不能为空");
			
		}
		//保存接口版本信息
		apiVersionManage.setApiId(apiManage.getId());
		apiVersionManage.setVersionNumber(versionNumber);
		apiVersionManage.setCreateTime(new Date());
		//待审核状态 待审核
		apiVersionManage.setApiVerifyStatus(ApiVerifyStatusEnum.WAIT_VERIFY.getStatus());
		//删除状态 正常
		apiVersionManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
		//接口版本是禁用
		apiVersionManage.setApiVersionStatus(ApiStatusEnum.DISABLE.getStatus());
		//修改方式是添加
		apiVersionManage.setChangeType(ChangeTypeEnum.ADD.getStatus());
		//验证sql模板
		if(StringUtil.isEmpty(apiVersionManage.getSqlTemplet())) {
			throw new SqlTempletIsNullExceptiuon("创建接口的时候sql模板语句不能为空!");
		}
		log.info("解析之前的Sql语句===="+apiVersionManage.getSqlTemplet());
		Statement statement = (Statement) CCJSqlParserUtil.parse(apiVersionManage.getSqlTemplet());
		log.info("通过SqlParser解析完成的Sql语句===="+statement);
		apiVersionManage.setSqlTemplet(statement.toString());
		apiVersionManageMapper.saveApiVersionManage(apiVersionManage);
		if(log.isInfoEnabled()) {
			log.info("apiVersionManage save success after id="+apiVersionManage.getId());
		}
		if(apiVersionManage.getId()==null) {
			throw new ApiVersionManageaveExceptiuon("接口版本保存异常");
		}
		if(apiOfTableList==null||apiOfTableList.size()<=0) {
			throw new ApiOfTableListIsNullExceptiuon("接口==》数据源==》数据表不能为空");
		}
		for (ApiOfTable apiOfTable : apiOfTableList) {
			apiOfTable.setApiVersionId(apiVersionManage.getId());
			apiOfTableMapper.insert(apiOfTable);
		}
		if(apiManage.getCreateMethod().equals(CreateMethodEnum.BYSQL.getStatus())) {
			Set<String> requestParamBySql = getWhereNameBySql(statement.toString());
			Set<String> responseParamBySql = getResponseParamBySql(statement.toString());
			doAddParamOrWhereBySql(apiManage,apiVersionManage,requestParamBySql,responseParamBySql);
		}
		if(apiManage.getCreateMethod().equals(CreateMethodEnum.VISUAL.getStatus())) {
			doAddParamOrWhere(apiManage,apiVersionManage,apiRequestParamList,apiResponseParamList,apiOfTableOfFieldList,updateFieldList,addFieldList);
		}
		 List<ApplyApi> applyApiList=new ArrayList<ApplyApi>();
		 ApplyApi applyApi=new ApplyApi();
		 applyApi.setApiId(apiManage.getId());
		 if(apiManage.getApplyId()==null) {
			 throw new ApplyIdIsNullExceptiuon("开发者中心保存接口应用的Id==applyId不能为null");
			 
		 }
		 //关联具体的应用
		 applyApi.setApplyId(apiManage.getApplyId());
		 applyApi.setApiVersion(versionNumber);
		 applyApi.setCreatedBy(apiVersionManage.getCreateBy());
		 applyApiList.add(applyApi);
		 applyManageMapper.saveApplyApi(applyApiList);
	}
	@Transactional(rollbackFor=Exception.class)
	public void adminSaveApiManage(ApiManagerParams apiManagerParams) 
			throws ApiManageSaveExceptiuon, ApiVersionManageIsNullExceptiuon, 
			ApiOfTableListIsNullExceptiuon, ApiOfTableOfFieldIsNullExceptiuon,
			ApiOfTableSaveExceptiuon, ApiRequestParamListIsNullExceptiuon, 
			ApiResponseParamListIsNullExceptiuon, ApiManageIsNullExceptiuon, ApiVersionManageaveExceptiuon, UpdateFieldListIsNullExceptiuon, AddFieldListIsNullExceptiuon, ApplyIdIsNullExceptiuon, ApiRequestParamDuplicatePenNameException, ApiResponseParamDuplicatePenNameException, UpdateFieldDuplicatePenNameException, AddFieldDuplicatePenNameException, RequestParamAndUpdateFieldDuplicatePenNameExceptiuon, JSQLParserException, SqlTempletIsNullExceptiuon, ApiRequestParamDuplicateBySqlException, ApiResponseParamDuplicateBySqlException, FileApiCatalogListIsNullExceptiuon, FileApiNameListIsNullExceptiuon, NameByUrlIsNullExceptiuon, NameByUrlIsDupExceptiuon {
		final String versionNumber="v1.00";
		ApiManage apiManage = apiManagerParams.getApiManage();
		List<ApiOfTable> apiOfTableList = apiManagerParams.getApiOfTableList();
		List<ApiOfTableOfField> apiOfTableOfFieldList = apiManagerParams.getApiOfTableOfFieldList();
		List<ApiRequestParam> apiRequestParamList = apiManagerParams.getApiRequestParamList();
		List<ApiResponseParam> apiResponseParamList = apiManagerParams.getApiResponseParamList();
		ApiVersionManage apiVersionManage = apiManagerParams.getApiVersionManage();
		List<UpdateField> updateFieldList = apiManagerParams.getUpdateFieldList();
		List<AddField> addFieldList = apiManagerParams.getAddFieldList();
		List<FileApiCatalog> fileApiCatalogList = apiManagerParams.getFileApiCatalogList();
		List<FileApiName> fileApiNameList = apiManagerParams.getFileApiNameList();
		if(apiManage==null) {
			throw new ApiManageIsNullExceptiuon("接口基本信息不能为空");
		}
		apiManage.setCreateTime(new Date());
		apiManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
		apiManage.setApiStatus(ApiStatusEnum.ENABLE.getStatus());
		apiManage.setUrl(API_PREFIX+apiManage.getUrl());
		apiManageMapper.saveApiManage(apiManage);
		if(log.isInfoEnabled()) {
			log.info("apiManage save success after id="+apiManage.getId());
		}
		//保存成功以后返回接口的Id
		if(apiManage.getId()==null) {
			throw new ApiManageSaveExceptiuon("接口基本信息保存异常");
			
		}
		if(apiVersionManage==null) {
			throw new ApiVersionManageIsNullExceptiuon("接口版本不能为空");
			
		}
		//保存接口版本信息
		apiVersionManage.setApiId(apiManage.getId());
		apiVersionManage.setVersionNumber(versionNumber);
		apiVersionManage.setCreateTime(new Date());
		//管理员自己创建的接口默认是审核通过
		apiVersionManage.setApiVerifyStatus(ApiVerifyStatusEnum.VERIFY_PASS.getStatus());
		//审核人就是创建人
		apiVersionManage.setVerifyBy(apiVersionManage.getCreateBy());
		//审核时间就是创建时间
		apiVersionManage.setVerifyTime(new Date());
		//删除状态 正常
		apiVersionManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
		//接口版本是可用
		apiVersionManage.setApiVersionStatus(ApiStatusEnum.ENABLE.getStatus());
		//修改方式是添加
		apiVersionManage.setChangeType(ChangeTypeEnum.ADD.getStatus());
		Statement statement=null;
		//2020-03-10
		if(!ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
			//验证sql模板是否合法
			if(StringUtil.isEmpty(apiVersionManage.getSqlTemplet())) {
				throw new SqlTempletIsNullExceptiuon("创建接口的时候sql模板语句不能为空!");
			}
	     statement = (Statement) CCJSqlParserUtil.parse(apiVersionManage.getSqlTemplet());
		apiVersionManage.setSqlTemplet(statement.toString());
		}
		apiVersionManage.setFileApiPath(apiVersionManage.getFileApiPath());
		apiVersionManageMapper.saveApiVersionManage(apiVersionManage);
		if(log.isInfoEnabled()) {
			log.info("apiVersionManage save success after id="+apiVersionManage.getId());
		}
		if(apiVersionManage.getId()==null) {
			throw new ApiVersionManageaveExceptiuon("接口版本保存异常");
		}
		if(!ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
			if(apiOfTableList==null||apiOfTableList.size()<=0) {
				throw new ApiOfTableListIsNullExceptiuon("接口==》数据源==》数据表不能为空");
			}
			for (ApiOfTable apiOfTable : apiOfTableList) {
				apiOfTable.setApiVersionId(apiVersionManage.getId());
				apiOfTableMapper.insert(apiOfTable);
			}
		}
		if(apiManage.getCreateMethod().equals(CreateMethodEnum.BYSQL.getStatus())) {
			Set<String> requestParamBySql = getWhereNameBySql(statement.toString());
			Set<String> responseParamBySql = getResponseParamBySql(statement.toString());
			doAddParamOrWhereBySql(apiManage,apiVersionManage,requestParamBySql,responseParamBySql);
		}
		if(apiManage.getCreateMethod().equals(CreateMethodEnum.VISUAL.getStatus())) {
			//doAddParamOrWhere(apiManage,apiVersionManage,apiRequestParamList,apiResponseParamList,apiOfTableOfFieldList,updateFieldList,addFieldList,fileApiCatalogList,fileApiNameList);
			if(ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
				log.info("文件接口的路径:"+apiVersionManage.getFileApiPath());
				List<String> namesByUrl = getNameByUrl(apiVersionManage.getFileApiPath());
				if(namesByUrl==null||namesByUrl.size()<=0) {
					throw new NameByUrlIsNullExceptiuon("保存文件接口必须有变量，且以${参数key}变量的形式");
				}
				if(isListDuplicat(namesByUrl)) {
					for (String name : namesByUrl) {
						ApiRequestParam arp=new ApiRequestParam();
						arp.setName(name);
						arp.setType("String");
						arp.setFieldDesc("文件接口的请求参数...");
						arp.setPenName(name);
						arp.setIsRequired(YesOrNoStatusEnum.YES.getStatus());
						apiRequestParamList.add(arp);
					}
				}else {
					throw new NameByUrlIsDupExceptiuon("接口文件保存${参数key}的参数key有重复，请修改以后才能保存");
					
				}
			}
			doAddParamOrWhereAndFile(apiManage, apiVersionManage, apiRequestParamList, apiResponseParamList, apiOfTableOfFieldList, updateFieldList, addFieldList, fileApiCatalogList, fileApiNameList);
		}
		if(apiManage.getApiType().equals(BUSINESS)) {
			List<ApplyApi> applyApiList=new ArrayList<ApplyApi>();
			ApplyApi applyApi=new ApplyApi();
			applyApi.setApiId(apiManage.getId());
			if(apiManage.getApplyId()==null) {
				throw new ApplyIdIsNullExceptiuon("接口管理==》business==》应用目录分类==》具体应用的applyId不能为null");
				
			}
			//关联具体的应用
			applyApi.setApplyId(apiManage.getApplyId());
			applyApi.setApiVersion(versionNumber);
			applyApi.setCreatedBy(apiVersionManage.getCreateBy());
			applyApiList.add(applyApi);
			applyManageMapper.saveApplyApi(applyApiList);
			
		}
		
	}
	
	@Transactional(rollbackFor=Exception.class)
	public void adminUpdateApiManage(ApiManagerParams apiManagerParams) 
			throws Exception {
		ApiManage apiManage = apiManagerParams.getApiManage();
		List<ApiOfTable> apiOfTableList = apiManagerParams.getApiOfTableList();
		List<ApiOfTableOfField> apiOfTableOfFieldList = apiManagerParams.getApiOfTableOfFieldList();
		List<ApiRequestParam> apiRequestParamList = apiManagerParams.getApiRequestParamList();
		List<ApiResponseParam> apiResponseParamList = apiManagerParams.getApiResponseParamList();
		ApiVersionManage apiVersionManage = apiManagerParams.getApiVersionManage();
		List<UpdateField> updateFieldList = apiManagerParams.getUpdateFieldList();
		List<AddField> addFieldList = apiManagerParams.getAddFieldList();
		List<FileApiCatalog> fileApiCatalogList = apiManagerParams.getFileApiCatalogList();
		List<FileApiName> fileApiNameList = apiManagerParams.getFileApiNameList();
		if(apiVersionManage.getId()==null) {
			throw new ApiVersionManageaveExceptiuon("接口版本的id不能为空");
		}
		ApiVersionManage existApiVersionManage = apiVersionManageMapper.selectByPrimaryKey(apiVersionManage.getId());
		if(existApiVersionManage.getApiVerifyStatus().equals(ApiVerifyStatusEnum.VERIFY_PASS.getStatus())) {
			//审核通过的修改需要做版本的增加
			//更新接口基本信息
			apiManage.setId(existApiVersionManage.getApiId());
			apiManage.setUpdateTime(new Date());
			apiManage.setUrl(API_PREFIX+apiManage.getUrl());
			apiManageMapper.updateByPrimaryKeySelective(apiManage);
			List<ApiVersionManage> apiVersionList = apiVersionManageMapper.selectApiVersionManageListByApiId(apiManage.getId());
			if(apiVersionList!=null) {
				for (ApiVersionManage avm : apiVersionList) {
					avm.setApiVersionStatus(ApiStatusEnum.DISABLE.getStatus());
					apiVersionManageMapper.updateByPrimaryKeySelective(avm);
				}
			}
			//接口版本以后的信息完全相当于新增
			//保存接口版本信息
			apiVersionManage.setId(null);
			apiVersionManage.setApiId(apiManage.getId());
			//拼接版本号
			double maxVersionNumber = getMaxVersionNumber(apiVersionManageMapper.selectApiVersionListByApiId(apiManage.getId()));
			double newVersion=maxVersionNumber+0.01;
			DecimalFormat df = new DecimalFormat("#.00");
			apiVersionManage.setVersionNumber("v"+df.format(newVersion));
			apiVersionManage.setCreateTime(new Date());
			//待审核状态 待审核
			apiVersionManage.setApiVerifyStatus(ApiVerifyStatusEnum.VERIFY_PASS.getStatus());
			//审核人就是修改人
			apiVersionManage.setVerifyBy(apiVersionManage.getCreateBy());
			//审核时间就是修改时间
			apiVersionManage.setVerifyTime(new Date());
			//删除状态 正常
			apiVersionManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
			//接口版本是禁用
			apiVersionManage.setApiVersionStatus(ApiStatusEnum.ENABLE.getStatus());
			//修改方式是添加
			apiVersionManage.setChangeType(ChangeTypeEnum.UPDATE.getStatus());
			//Statement statement=null;
		/*	if(!ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
				//验证sql模板是否合法
				if(StringUtil.isEmpty(apiVersionManage.getSqlTemplet())) {
					throw new SqlTempletIsNullExceptiuon("创建接口的时候sql模板语句不能为空!");
				}
			log.info("解析之前的Sql语句===="+apiVersionManage.getSqlTemplet());
			 statement = (Statement) CCJSqlParserUtil.parse(apiVersionManage.getSqlTemplet());
			log.info("通过SqlParser解析完成的Sql语句===="+statement);
			apiVersionManage.setSqlTemplet(statement.toString());
			}*/
			apiVersionManage.setFileApiPath(apiVersionManage.getFileApiPath());
			apiVersionManageMapper.saveApiVersionManage(apiVersionManage);
			if(log.isInfoEnabled()) {
				log.info("apiVersionManage save success after id="+apiVersionManage.getId());
			}
			String cacheKey=(apiManage.getRequestMethod().toLowerCase()+apiManage.getUrl()).replace("/", ":");
				if(CacheExsite.isExsite(cacheKey)) {
					//缓存中存在，需要删除key,因为访问接口的时候，执行的sql语句是从缓存中取出的
					CacheCom.del(cacheKey);
				}
			if(apiVersionManage.getId()==null) {
				throw new ApiVersionManageaveExceptiuon("接口版本保存异常");
			}
			if(!ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
				if(apiOfTableList==null||apiOfTableList.size()<=0) {
					throw new ApiOfTableListIsNullExceptiuon("接口==》数据源==》数据表不能为空");
				}
				
				for (ApiOfTable apiOfTable : apiOfTableList) {
					apiOfTable.setApiVersionId(apiVersionManage.getId());
					apiOfTableMapper.insert(apiOfTable);
				}
		   }
			if(apiManage.getCreateMethod().equals(CreateMethodEnum.BYSQL.getStatus())) {
				Set<String> requestParamBySql = getWhereNameBySql(apiVersionManage.getSqlTemplet() );
				Set<String> responseParamBySql = getResponseParamBySql(apiVersionManage.getSqlTemplet());
//				Set<String> requestParamBySql = getWhereNameBySql(statement.toString());
//				Set<String> responseParamBySql = getResponseParamBySql(statement.toString());
				doAddParamOrWhereBySql(apiManage,apiVersionManage,requestParamBySql,responseParamBySql);
			}
			if(apiManage.getCreateMethod().equals(CreateMethodEnum.VISUAL.getStatus())) {
				//doAddParamOrWhere(apiManage,apiVersionManage,apiRequestParamList,apiResponseParamList,apiOfTableOfFieldList,updateFieldList,addFieldList);
				if(ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
					log.info("文件接口的路径:"+apiVersionManage.getFileApiPath());
					List<String> namesByUrl = getNameByUrl(apiVersionManage.getFileApiPath());
					if(namesByUrl==null||namesByUrl.size()<=0) {
						throw new NameByUrlIsNullExceptiuon("保存文件接口必须有变量，且以${参数key}变量的形式");
					}
					if(isListDuplicat(namesByUrl)) {
						for (String name : namesByUrl) {
							ApiRequestParam arp=new ApiRequestParam();
							arp.setName(name);
							arp.setType("String");
							arp.setFieldDesc("文件接口的请求参数...");
							arp.setPenName(name);
							arp.setIsRequired(YesOrNoStatusEnum.YES.getStatus());
							apiRequestParamList.add(arp);
						}
					}else {
						throw new NameByUrlIsDupExceptiuon("接口文件保存${参数key}的参数key有重复，请修改以后才能保存");
						
					}
				}
				doAddParamOrWhereAndFile(apiManage, apiVersionManage, apiRequestParamList, apiResponseParamList, apiOfTableOfFieldList, updateFieldList, addFieldList, fileApiCatalogList, fileApiNameList);
			}
			
		}else {
			//别的状态下修改就不需要版本的叠加
			//更新接口基本信息
			apiManage.setId(existApiVersionManage.getApiId());
			apiManage.setUpdateTime(new Date());
			apiManage.setUrl(API_PREFIX+apiManage.getUrl());
			apiManageMapper.updateByPrimaryKeySelective(apiManage);
			//更新接口版本的信息
			apiVersionManage.setChangeType(ChangeTypeEnum.UPDATE.getStatus());
			Statement statement=null;
			if(!ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
			//验证sql模板是否合法
			if(StringUtil.isEmpty(apiVersionManage.getSqlTemplet())) {
				throw new SqlTempletIsNullExceptiuon("创建接口的时候sql模板语句不能为空!");
			}
			log.info("解析之前的Sql语句===="+apiVersionManage.getSqlTemplet());
			 statement = (Statement) CCJSqlParserUtil.parse(apiVersionManage.getSqlTemplet());
			log.info("通过SqlParser解析完成的Sql语句===="+statement);
			apiVersionManage.setSqlTemplet(statement.toString());
			}
			apiVersionManageMapper.updateByPrimaryKeySelective(apiVersionManage);
			//删除已经存在的信息
			deleteApiVersionAttachInfo(apiVersionManage.getId());
			if(!ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
				if(apiOfTableList==null||apiOfTableList.size()<=0) {
					throw new ApiOfTableListIsNullExceptiuon("接口==》数据源==》数据表不能为空");
				}
				for (ApiOfTable apiOfTable : apiOfTableList) {
					apiOfTable.setApiVersionId(apiVersionManage.getId());
					apiOfTableMapper.insert(apiOfTable);
				}
			}
			if(apiManage.getCreateMethod().equals(CreateMethodEnum.BYSQL.getStatus())) {
				Set<String> requestParamBySql = getWhereNameBySql(statement.toString());
				Set<String> responseParamBySql = getResponseParamBySql(statement.toString());
				doAddParamOrWhereBySql(apiManage,apiVersionManage,requestParamBySql,responseParamBySql);
			}
			if(apiManage.getCreateMethod().equals(CreateMethodEnum.VISUAL.getStatus())) {
				//doAddParamOrWhere(apiManage,apiVersionManage,apiRequestParamList,apiResponseParamList,apiOfTableOfFieldList,updateFieldList,addFieldList);
				if(ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
					log.info("文件接口的路径:"+apiVersionManage.getFileApiPath());
					List<String> namesByUrl = getNameByUrl(apiVersionManage.getFileApiPath());
					if(namesByUrl==null||namesByUrl.size()<=0) {
						throw new NameByUrlIsNullExceptiuon("保存文件接口必须有变量，且以${参数key}变量的形式");
					}
					if(isListDuplicat(namesByUrl)) {
						for (String name : namesByUrl) {
							ApiRequestParam arp=new ApiRequestParam();
							arp.setName(name);
							arp.setType("String");
							arp.setFieldDesc("文件接口的请求参数...");
							arp.setPenName(name);
							arp.setIsRequired(YesOrNoStatusEnum.YES.getStatus());
							apiRequestParamList.add(arp);
						}
					}else {
						throw new NameByUrlIsDupExceptiuon("接口文件保存${参数key}的参数key有重复，请修改以后才能保存");
						
					}
				}
				doAddParamOrWhereAndFile(apiManage, apiVersionManage, apiRequestParamList, apiResponseParamList, apiOfTableOfFieldList, updateFieldList, addFieldList, fileApiCatalogList, fileApiNameList);
			}
		}
	}
	@Transactional(rollbackFor=Exception.class)
	public void updateApiManage(ApiManagerParams apiManagerParams) 
			throws ApiVersionManageaveExceptiuon, 
			ApiOfTableListIsNullExceptiuon, ApiOfTableOfFieldIsNullExceptiuon,
			ApiRequestParamListIsNullExceptiuon, ApiResponseParamListIsNullExceptiuon, UpdateFieldListIsNullExceptiuon, AddFieldListIsNullExceptiuon, ApiRequestParamDuplicatePenNameException, ApiResponseParamDuplicatePenNameException, UpdateFieldDuplicatePenNameException, AddFieldDuplicatePenNameException, RequestParamAndUpdateFieldDuplicatePenNameExceptiuon, SqlTempletIsNullExceptiuon, JSQLParserException, ApiRequestParamDuplicateBySqlException, ApiResponseParamDuplicateBySqlException, ApiStatusDisableExceptiuon, ApiVersionStatusDisableExceptiuon {
		ApiManage apiManage = apiManagerParams.getApiManage();
		List<ApiOfTable> apiOfTableList = apiManagerParams.getApiOfTableList();
		List<ApiOfTableOfField> apiOfTableOfFieldList = apiManagerParams.getApiOfTableOfFieldList();
		List<ApiRequestParam> apiRequestParamList = apiManagerParams.getApiRequestParamList();
		List<ApiResponseParam> apiResponseParamList = apiManagerParams.getApiResponseParamList();
		ApiVersionManage apiVersionManage = apiManagerParams.getApiVersionManage();
		List<UpdateField> updateFieldList = apiManagerParams.getUpdateFieldList();
		List<AddField> addFieldList = apiManagerParams.getAddFieldList();
		if(apiVersionManage.getId()==null) {
			throw new ApiVersionManageaveExceptiuon("接口版本的id不能为空");
		}
		ApiVersionManage existApiVersionManage = apiVersionManageMapper.selectByPrimaryKey(apiVersionManage.getId());
		ApiManage exitApiManage = apiManageMapper.selectApiManageByPrimaryKey(existApiVersionManage.getApiId());
		if(ApiStatusEnum.DISABLE.getStatus().equals(exitApiManage.getApiStatus())) {
			throw new ApiStatusDisableExceptiuon("当前接口处于禁用状态，请联系管理员!");
		}
		if(ApiStatusEnum.DISABLE.getStatus().equals(existApiVersionManage.getApiVersionStatus())) {
			throw new ApiVersionStatusDisableExceptiuon("当前接口版本处于停用状态，请联系管理员!");
		}
		if(existApiVersionManage.getApiVerifyStatus().equals(ApiVerifyStatusEnum.VERIFY_PASS.getStatus())) {
			//审核通过的修改需要做版本的增加
			//更新接口基本信息
			apiManage.setId(existApiVersionManage.getApiId());
			apiManage.setUpdateTime(new Date());
			apiManage.setUrl(API_PREFIX+apiManage.getUrl());
			apiManageMapper.updateByPrimaryKeySelective(apiManage);
			//接口版本以后的信息完全相当于新增
			//保存接口版本信息
			apiVersionManage.setId(null);
			apiVersionManage.setApiId(apiManage.getId());
			//拼接版本号
			double maxVersionNumber = getMaxVersionNumber(apiVersionManageMapper.selectApiVersionListByApiId(existApiVersionManage.getApiId()));
			double newVersion=maxVersionNumber+0.01;
			DecimalFormat df = new DecimalFormat("#.00");
			String versionData = df.format(newVersion);
			apiVersionManage.setVersionNumber("v"+versionData);
			apiVersionManage.setCreateTime(new Date());
			//待审核状态 待审核
			apiVersionManage.setApiVerifyStatus(ApiVerifyStatusEnum.WAIT_VERIFY.getStatus());
			//删除状态 正常
			apiVersionManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
			//接口版本是禁用
			apiVersionManage.setApiVersionStatus(ApiStatusEnum.DISABLE.getStatus());
			//修改方式是添加
			apiVersionManage.setChangeType(ChangeTypeEnum.UPDATE.getStatus());
			//验证sql模板是否合法
			if(StringUtil.isEmpty(apiVersionManage.getSqlTemplet())) {
				throw new SqlTempletIsNullExceptiuon("创建接口的时候sql模板语句不能为空!");
			}
			log.info("解析之前的Sql语句===="+apiVersionManage.getSqlTemplet());
			Statement statement = (Statement) CCJSqlParserUtil.parse(apiVersionManage.getSqlTemplet());
			log.info("通过SqlParser解析完成的Sql语句===="+statement);
			apiVersionManage.setSqlTemplet(statement.toString());
			apiVersionManageMapper.saveApiVersionManage(apiVersionManage);
			if(log.isInfoEnabled()) {
				log.info("apiVersionManage save success after id="+apiVersionManage.getId());
			}
			if(apiVersionManage.getId()==null) {
				throw new ApiVersionManageaveExceptiuon("接口版本保存异常");
			}
			if(apiOfTableList==null||apiOfTableList.size()<=0) {
				throw new ApiOfTableListIsNullExceptiuon("接口==》数据源==》数据表不能为空");
			}
			
			for (ApiOfTable apiOfTable : apiOfTableList) {
				apiOfTable.setApiVersionId(apiVersionManage.getId());
				apiOfTableMapper.insert(apiOfTable);
			}
			if(apiManage.getCreateMethod().equals(CreateMethodEnum.BYSQL.getStatus())) {
				Set<String> requestParamBySql = getWhereNameBySql(statement.toString());
				Set<String> responseParamBySql = getResponseParamBySql(statement.toString());
				doAddParamOrWhereBySql(apiManage,apiVersionManage,requestParamBySql,responseParamBySql);
			}
			if(apiManage.getCreateMethod().equals(CreateMethodEnum.VISUAL.getStatus())) {
				doAddParamOrWhere(apiManage,apiVersionManage,apiRequestParamList,apiResponseParamList,apiOfTableOfFieldList,updateFieldList,addFieldList);
			}
			
		}else {
			//别的状态下修改就不需要版本的叠加
			//更新接口基本信息
			apiManage.setId(existApiVersionManage.getApiId());
			apiManage.setUpdateTime(new Date());
			apiManage.setUrl(API_PREFIX+apiManage.getUrl());
			apiManageMapper.updateByPrimaryKeySelective(apiManage);
			//待审核状态 待审核
			apiVersionManage.setApiVerifyStatus(ApiVerifyStatusEnum.WAIT_VERIFY.getStatus());
			//删除状态 正常
			apiVersionManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
			//接口版本是禁用
			apiVersionManage.setApiVersionStatus(ApiStatusEnum.DISABLE.getStatus());
			//修改方式是添加
			apiVersionManage.setChangeType(ChangeTypeEnum.UPDATE.getStatus());
			//验证sql模板是否合法
			if(StringUtil.isEmpty(apiVersionManage.getSqlTemplet())) {
				throw new SqlTempletIsNullExceptiuon("创建接口的时候sql模板语句不能为空!");
			}
			log.info("解析之前的Sql语句===="+apiVersionManage.getSqlTemplet());
			Statement statement = (Statement) CCJSqlParserUtil.parse(apiVersionManage.getSqlTemplet());
			log.info("通过SqlParser解析完成的Sql语句===="+statement);
			apiVersionManage.setSqlTemplet(statement.toString());
			apiVersionManageMapper.updateByPrimaryKeySelective(apiVersionManage);
			//删除已经存在的信息
			deleteApiVersionAttachInfo(apiVersionManage.getId());
			
			if(apiOfTableList==null||apiOfTableList.size()<=0) {
				throw new ApiOfTableListIsNullExceptiuon("接口==》数据源==》数据表不能为空");
			}
			for (ApiOfTable apiOfTable : apiOfTableList) {
				apiOfTable.setApiVersionId(apiVersionManage.getId());
				apiOfTableMapper.insert(apiOfTable);
			}
			if(apiManage.getCreateMethod().equals(CreateMethodEnum.BYSQL.getStatus())) {
				Set<String> requestParamBySql = getWhereNameBySql(statement.toString());
				Set<String> responseParamBySql = getResponseParamBySql(statement.toString());
				doAddParamOrWhereBySql(apiManage,apiVersionManage,requestParamBySql,responseParamBySql);
			}
			if(apiManage.getCreateMethod().equals(CreateMethodEnum.VISUAL.getStatus())) {
				doAddParamOrWhere(apiManage,apiVersionManage,apiRequestParamList,apiResponseParamList,apiOfTableOfFieldList,updateFieldList,addFieldList);
			}
		}
	}
	//@Transactional(rollbackFor=Exception.class)
	public void doAddParamOrWhere(ApiManage apiManage,ApiVersionManage apiVersionManage, List<ApiRequestParam> apiRequestParamList,
			List<ApiResponseParam> apiResponseParamList, List<ApiOfTableOfField> apiOfTableOfFieldList,
			List<UpdateField> updateFieldList, List<AddField> addFieldList) 
					throws ApiRequestParamListIsNullExceptiuon, ApiResponseParamListIsNullExceptiuon, 
					ApiOfTableOfFieldIsNullExceptiuon, UpdateFieldListIsNullExceptiuon, AddFieldListIsNullExceptiuon,
					ApiRequestParamDuplicatePenNameException, ApiResponseParamDuplicatePenNameException, 
					UpdateFieldDuplicatePenNameException, AddFieldDuplicatePenNameException, RequestParamAndUpdateFieldDuplicatePenNameExceptiuon {
		if(apiOfTableOfFieldList!=null &&apiOfTableOfFieldList.size()>0) {
			for (ApiOfTableOfField apiOfTableOfField : apiOfTableOfFieldList) {
				apiOfTableOfField.setApiVersionId(apiVersionManage.getId());
				apiOfTableOfFieldMapper.insert(apiOfTableOfField);
			}
		}
		if(apiManage.getRequestMethod().equals(requestMethodGet)) {
			if(apiRequestParamList!=null && apiRequestParamList.size()>0) {
				if(isApiRequestParamDuplicatePenName(apiRequestParamList)) {
					throw new ApiRequestParamDuplicatePenNameException("Get请求接口保存的时候,请求参数的笔名有重复值,请检查并修改以后方可保存!");
				}
				for (ApiRequestParam apiRequestParam : apiRequestParamList) {
					apiRequestParam.setApiVersionId(apiVersionManage.getId());
					apiRequestParamMapper.insert(apiRequestParam);
				}
				//throw new ApiRequestParamListIsNullExceptiuon("Get请求接口保存的时候,请求参数不能为空!");
			}
			if(apiResponseParamList==null||apiResponseParamList.size()<=0) {
				throw new ApiResponseParamListIsNullExceptiuon("Get请求接口保存的时候,响应参数不能为空");
			}
			if(isApiResponseParamDuplicatePenName(apiResponseParamList)) {
				throw new ApiResponseParamDuplicatePenNameException("Get请求接口保存的时候,响应参数的笔名有重复值,请检查并修改以后方可保存!");
			}
			for (ApiResponseParam apiResponseParam : apiResponseParamList) {
				apiResponseParam.setApiVersionId(apiVersionManage.getId());
				apiResponseParamMapper.insert(apiResponseParam);
			}
			
		}else if(apiManage.getRequestMethod().equals(requestMethodPut)) {
			Set<String> requestParamAndUpdateField=new HashSet<String>();
			if(apiRequestParamList==null||apiRequestParamList.size()<=0) {
				throw new ApiRequestParamListIsNullExceptiuon("PUT请求接口保存的时候,请求参数不能为空!");
			}
			if(isApiRequestParamDuplicatePenName(apiRequestParamList)) {
				throw new ApiRequestParamDuplicatePenNameException("PUT请求接口保存的时候,请求参数的笔名有重复值,请检查并修改以后方可保存!");
			}
			for (ApiRequestParam apiRequestParam : apiRequestParamList) {
				requestParamAndUpdateField.add(apiRequestParam.getPenName());
				apiRequestParam.setApiVersionId(apiVersionManage.getId());
				apiRequestParamMapper.insert(apiRequestParam);
			}
			if(updateFieldList==null||updateFieldList.size()<=0) {
				throw new UpdateFieldListIsNullExceptiuon("PUT请求接口保存的时候,修改字段不能为空!");
			}
			if(isUpdateFieldDuplicatePenName(updateFieldList)) {
				throw new UpdateFieldDuplicatePenNameException("PUT请求接口保存的时候,修改参数的笔名有重复值,请检查并修改以后方可保存!");
			}
			for (UpdateField updateField : updateFieldList) {
				requestParamAndUpdateField.add(updateField.getPenName());
				updateField.setApiVersionId(apiVersionManage.getId());
				updateFieldMapper.insert(updateField);
			}
			if(requestParamAndUpdateField.size()!=apiRequestParamList.size()+updateFieldList.size()){
				throw new RequestParamAndUpdateFieldDuplicatePenNameExceptiuon("PUT请求接口保存的时候,请求参数的笔名和修改字段笔名不能重复,请检查并修改以后再保存!");
			}
			
		}else if(apiManage.getRequestMethod().equals(requestMethodPost)) {
			if(addFieldList==null || addFieldList.size()<=0) {
				throw new AddFieldListIsNullExceptiuon("POST请求接口保存的时候,插入字段不能为空!");
			}
			if(isAddFieldDuplicatePenName(addFieldList)) {
				throw new AddFieldDuplicatePenNameException("POST请求接口保存的时候,插入参数的笔名有重复值,请检查并修改以后方可保存!");
			}
			for (AddField addField : addFieldList) {
				addField.setApiVersionId(apiVersionManage.getId());
				addFieldMapper.insert(addField);
				
			}
			
		}else if(apiManage.getRequestMethod().equals(requestMethodDelete)) {
			if(apiRequestParamList==null||apiRequestParamList.size()<=0) {
				throw new ApiRequestParamListIsNullExceptiuon("请求参数不能为空");
			}
			if(isApiRequestParamDuplicatePenName(apiRequestParamList)) {
				throw new ApiRequestParamDuplicatePenNameException("DELETE请求接口保存的时候,请求参数的笔名有重复值,请检查并修改以后方可保存!");
			}
			for (ApiRequestParam apiRequestParam : apiRequestParamList) {
				apiRequestParam.setApiVersionId(apiVersionManage.getId());
				apiRequestParamMapper.insert(apiRequestParam);
			}
		}
		
	}
	public void doAddParamOrWhereAndFile(ApiManage apiManage,ApiVersionManage apiVersionManage, List<ApiRequestParam> apiRequestParamList,
			List<ApiResponseParam> apiResponseParamList, List<ApiOfTableOfField> apiOfTableOfFieldList,
			List<UpdateField> updateFieldList, List<AddField> addFieldList,List<FileApiCatalog> fileApiCatalogList,List<FileApiName> fileApiNameList) 
					throws ApiRequestParamListIsNullExceptiuon, ApiResponseParamListIsNullExceptiuon, 
					ApiOfTableOfFieldIsNullExceptiuon, UpdateFieldListIsNullExceptiuon, AddFieldListIsNullExceptiuon,
					ApiRequestParamDuplicatePenNameException, ApiResponseParamDuplicatePenNameException, 
					UpdateFieldDuplicatePenNameException, AddFieldDuplicatePenNameException, RequestParamAndUpdateFieldDuplicatePenNameExceptiuon, FileApiCatalogListIsNullExceptiuon, FileApiNameListIsNullExceptiuon {
		if(apiOfTableOfFieldList!=null &&apiOfTableOfFieldList.size()>0) {
			for (ApiOfTableOfField apiOfTableOfField : apiOfTableOfFieldList) {
				apiOfTableOfField.setApiVersionId(apiVersionManage.getId());
				apiOfTableOfFieldMapper.insert(apiOfTableOfField);
			}
		}
		if(apiManage.getRequestMethod().equals(requestMethodGet)) {
			if(apiRequestParamList!=null && apiRequestParamList.size()>0) {
				if(isApiRequestParamDuplicatePenName(apiRequestParamList)) {
					throw new ApiRequestParamDuplicatePenNameException("Get请求接口保存的时候,请求参数的笔名有重复值,请检查并修改以后方可保存!");
				}
				for (ApiRequestParam apiRequestParam : apiRequestParamList) {
					apiRequestParam.setApiVersionId(apiVersionManage.getId());
					apiRequestParamMapper.insert(apiRequestParam);
				}
				//throw new ApiRequestParamListIsNullExceptiuon("Get请求接口保存的时候,请求参数不能为空!");
			}
			if(ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
				if(fileApiCatalogList==null||fileApiCatalogList.size()<=0) {
					throw new FileApiCatalogListIsNullExceptiuon("文件接口的目录文件参数不能为空!");
					
				}
				for (FileApiCatalog fileApiCatalog : fileApiCatalogList) {
					fileApiCatalog.setApiVersionId(apiVersionManage.getId());
					fileApiCatalogMapper.insert(fileApiCatalog);
					
				}
				if(fileApiNameList==null||fileApiNameList.size()<=0) {
					throw new FileApiNameListIsNullExceptiuon("文件接口的文件名称参数不能为空!");
					
				}
				for (FileApiName fileApiName : fileApiNameList) {
					fileApiName.setApiVersionId(apiVersionManage.getId());
					fileApiNameMapper.insert(fileApiName);
				}
			}
			if(!ApiRequestModeStatusEnum.FILE.getStatus().equals(apiManage.getIsOutSide())) {
				if(apiResponseParamList==null||apiResponseParamList.size()<=0) {
					throw new ApiResponseParamListIsNullExceptiuon("Get请求接口保存的时候,响应参数不能为空");
				}
				if(isApiResponseParamDuplicatePenName(apiResponseParamList)) {
					throw new ApiResponseParamDuplicatePenNameException("Get请求接口保存的时候,响应参数的笔名有重复值,请检查并修改以后方可保存!");
				}
				for (ApiResponseParam apiResponseParam : apiResponseParamList) {
					apiResponseParam.setApiVersionId(apiVersionManage.getId());
					apiResponseParamMapper.insert(apiResponseParam);
				}
			}
			
		}else if(apiManage.getRequestMethod().equals(requestMethodPut)) {
			Set<String> requestParamAndUpdateField=new HashSet<String>();
			if(apiRequestParamList==null||apiRequestParamList.size()<=0) {
				throw new ApiRequestParamListIsNullExceptiuon("PUT请求接口保存的时候,请求参数不能为空!");
			}
			if(isApiRequestParamDuplicatePenName(apiRequestParamList)) {
				throw new ApiRequestParamDuplicatePenNameException("PUT请求接口保存的时候,请求参数的笔名有重复值,请检查并修改以后方可保存!");
			}
			for (ApiRequestParam apiRequestParam : apiRequestParamList) {
				requestParamAndUpdateField.add(apiRequestParam.getPenName());
				apiRequestParam.setApiVersionId(apiVersionManage.getId());
				apiRequestParamMapper.insert(apiRequestParam);
			}
			if(updateFieldList==null||updateFieldList.size()<=0) {
				throw new UpdateFieldListIsNullExceptiuon("PUT请求接口保存的时候,修改字段不能为空!");
			}
			if(isUpdateFieldDuplicatePenName(updateFieldList)) {
				throw new UpdateFieldDuplicatePenNameException("PUT请求接口保存的时候,修改参数的笔名有重复值,请检查并修改以后方可保存!");
			}
			for (UpdateField updateField : updateFieldList) {
				requestParamAndUpdateField.add(updateField.getPenName());
				updateField.setApiVersionId(apiVersionManage.getId());
				updateFieldMapper.insert(updateField);
			}
			if(requestParamAndUpdateField.size()!=apiRequestParamList.size()+updateFieldList.size()){
				throw new RequestParamAndUpdateFieldDuplicatePenNameExceptiuon("PUT请求接口保存的时候,请求参数的笔名和修改字段笔名不能重复,请检查并修改以后再保存!");
			}
			
		}else if(apiManage.getRequestMethod().equals(requestMethodPost)) {
			if(addFieldList==null || addFieldList.size()<=0) {
				throw new AddFieldListIsNullExceptiuon("POST请求接口保存的时候,插入字段不能为空!");
			}
			if(isAddFieldDuplicatePenName(addFieldList)) {
				throw new AddFieldDuplicatePenNameException("POST请求接口保存的时候,插入参数的笔名有重复值,请检查并修改以后方可保存!");
			}
			for (AddField addField : addFieldList) {
				addField.setApiVersionId(apiVersionManage.getId());
				addFieldMapper.insert(addField);
				
			}
			
		}else if(apiManage.getRequestMethod().equals(requestMethodDelete)) {
			if(apiRequestParamList==null||apiRequestParamList.size()<=0) {
				throw new ApiRequestParamListIsNullExceptiuon("请求参数不能为空");
			}
			if(isApiRequestParamDuplicatePenName(apiRequestParamList)) {
				throw new ApiRequestParamDuplicatePenNameException("DELETE请求接口保存的时候,请求参数的笔名有重复值,请检查并修改以后方可保存!");
			}
			for (ApiRequestParam apiRequestParam : apiRequestParamList) {
				apiRequestParam.setApiVersionId(apiVersionManage.getId());
				apiRequestParamMapper.insert(apiRequestParam);
			}
		}
		
	}
	public void doAddParamOrWhereBySql(ApiManage apiManage,ApiVersionManage apiVersionManage, Set<String> apiRequestParamList,Set<String> apiResponseParamList) throws ApiResponseParamListIsNullExceptiuon, ApiRequestParamDuplicateBySqlException, ApiResponseParamDuplicateBySqlException {
		if(CollectionUtils.isNotEmpty(apiRequestParamList)) {
			for (String apiRequestParam : apiRequestParamList) {
				ApiRequestParam requestParam=new ApiRequestParam();
				requestParam.setApiVersionId(apiVersionManage.getId());
				requestParam.setName(apiRequestParam);
				requestParam.setIsRequired(YesOrNoStatusEnum.YES.getStatus());
				requestParam.setPenName(apiRequestParam);
				requestParam.setType("String");
				apiRequestParamMapper.insert(requestParam);
			}
		}
		if(CollectionUtils.isEmpty(apiResponseParamList)) {
			throw new ApiResponseParamListIsNullExceptiuon("Get请求并且通过SQL方式创建接口保存的时候,返回字段不能为空,即不能使用select *查询语句,请给出from 后面表中具体的查询字段!");
		}
		if(CollectionUtils.isNotEmpty(apiResponseParamList) && apiResponseParamList.contains("*")){
			throw new ApiResponseParamListIsNullExceptiuon("Get请求并且通过SQL方式创建接口保存的时候,需要指定具体表中的查询字段，即不能使用select *或者select t.*查询语句,请给出from 后面表中具体的查询字段!");
		}
		//if(isApiResponseParamDuplicateBySql(apiResponseParamList)) {
			//throw new ApiResponseParamDuplicateBySqlException("Get请求并且通过SQL方式创建接口保存的时候,响应参数的笔名有重复值,请检查并修改以后方可保存!");
		//}
		for (String apiResponseParam : apiResponseParamList) {
			ApiResponseParam responseParam=new ApiResponseParam();
			responseParam.setApiVersionId(apiVersionManage.getId());
			responseParam.setName(apiResponseParam);
			responseParam.setPenName(apiResponseParam);
			responseParam.setIsRequired(YesOrNoStatusEnum.YES.getStatus());
			responseParam.setType("String");
			apiResponseParamMapper.insert(responseParam);
		}
	}
	private boolean isApiResponseParamDuplicateBySql(List<String> apiResponseParamList) {
		Set<String> responseList=new HashSet<String>();
		for (String string : apiResponseParamList) {
			responseList.add(string.toLowerCase());
		}
		if(responseList.size()!=apiResponseParamList.size()) {
			return true;
		}
		return false;
	}
	private boolean isApiRequestParamDuplicateBySql(List<String> apiRequestParamList) {
		if(apiRequestParamList!=null &&apiRequestParamList.size()>0) {
			Set<String> requestList=new HashSet<String>(apiRequestParamList);
			if(apiRequestParamList.size()!=requestList.size()) {
				return true;
			}
			
		}
		return false;
	}
	public void deleteApiManageById(Integer id) {
		apiManageMapper.deleteByPrimaryKey(id);

	}

	public ApiManage selectByPrimaryKey(Integer id) {
		return apiManageMapper.selectByPrimaryKey(id);
	}
	/**
	 * 
	 * @Description:根据查询条件分页查询接口列表 
	 * @date: 2019年3月14日 上午10:52:02
	 * @author:wangshunyi 
	 * @throws
	 */
	public PageInfo selectPageBySearchParams(Integer pageNum, Integer pageSize, String name, String url,Integer applyId) {
		PageHelper.startPage(pageNum, pageSize);
		Map<String, Object> paraMap = new HashMap<>();
		paraMap.put("name", name);
		paraMap.put("url", url);
		paraMap.put("applyId", applyId);
		List<ApiManage> apiManageList = apiManageMapper.selectListBySearchParams(paraMap);
		PageInfo pageInfo=new PageInfo(apiManageList);
		return pageInfo;
	}

	public ApiManage selectApiManageAndApiversionIdByApiIdAndVersionStatusAndVerifyStatusAndDeleteStatus(String url) {
		return apiManageMapper.selectApiManageAndApiversionIdByApiIdAndVersionStatusAndVerifyStatusAndDeleteStatus(url);

	}

	public Map<String,Object> getApiManageDetails(Integer id,String versionCount) {
		 ApiManage apiManage = apiManageMapper.selectApiManageByPrimaryKey(id);
		 Map<String,Object> paramMap=new HashMap<String,Object>();
		 paramMap.put("apiId", id);
		 paramMap.put("versionCount", versionCount);
		 ApiVersionManage apiVersionManage = apiVersionManageMapper.selectApiVersionManageByApiIdAndVersion(paramMap);
		 List<Map<String,Object>> tableList=new ArrayList<Map<String,Object>>();
		 List<Map<String,Object>> fieldList=new ArrayList<Map<String,Object>>();
		 Map<String,Object> resultMap=new HashMap<String,Object>();
		 List<ApiOfTableOfField> apiOfTableOfFieldList=null;
		 if(apiManage!=null && apiVersionManage!=null) {
			 apiOfTableOfFieldList = apiOfTableOfFieldMapper.selectApiOfTableOfFieldListByApiVersionId(apiVersionManage.getId());
			 List<ApiOfTable> apiOfTableList = apiOfTableMapper.selectApiOfTableByApiVersionId(apiVersionManage.getId());
			 if(apiOfTableList!=null||apiOfTableList.size()>0) {
				 for (ApiOfTable apiOfTable : apiOfTableList) {
					 Map<String,Object> tableMap=new HashMap<String,Object>();
					 MetadataBasic metadataBasic = metadataBasicMapper.getMetadataBasicId(apiOfTable.getTableId());
					 if(metadataBasic!=null) {
					 tableMap.put("id", metadataBasic.getId());
					 tableMap.put("tableName", metadataBasic.getTableName());
					 tableList.add(tableMap);
					/* for (ApiOfTableOfField apiOfTableOfField : apiOfTableOfFieldList) {
						 Map<String,Object> filedMap=new HashMap<String,Object>();
						 MetadataElement metadataElement = metadataElementMapper.getMetadataElementByFieldId(apiOfTableOfField.getFieldId());
						 if(metadataElement!=null) {
						 filedMap.put("fieldId", metadataElement.getId());
						 filedMap.put("fieldName", metadataElement.getFieldName());
						 filedMap.put("tableId", metadataBasic.getId());
						 fieldList.add(filedMap);
						 }
					 }*/
						
					}
				}
			 }
			 List<ApiRequestParam> apiRequestParamList = apiRequestParamMapper.selectApiRequestParamListByApiVersionId(apiVersionManage.getId());
			 if(StringUtils.isNotEmpty(apiManage) && apiManage.getIsOutSide().equals(ApiRequestModeStatusEnum.YES.getStatus())) {
				Map<String,Object> param=new HashMap<String,Object>();
				 for (ApiRequestParam apiRequestParam : apiRequestParamList) {
					 param.put(apiRequestParam.getName(), apiRequestParam.getName());
				}
				 String url = getUrlStrParamsByMap(apiManage.getUrl(),param);
				 log.info(">>>还原以后的第三方请求接口地址="+url);
				 apiManage.setUrl(url);
			 }
			 List<ApiResponseParam> apiResponseParamList = apiResponseParamMapper.selectApiResponseParamListByApiVersionId(apiVersionManage.getId());
			 List<UpdateField> updateFieldList = updateFieldMapper.selectUpdateFieldListByApiVersionId(apiVersionManage.getId());
			 List<AddField> addFieldList = addFieldMapper.selectAddFieldListByApiVersionId(apiVersionManage.getId());
			 List<FileApiCatalog> fileApiCatalogList = fileApiCatalogMapper.selectFileApiCatalogByApiVersionId(apiVersionManage.getId());
			 List<FileApiName> fileApiNameList = fileApiNameMapper.selectFileApiNameByApiVersionId(apiVersionManage.getId());
		     resultMap.put("apiBasicInfo", apiManage);
		     resultMap.put("tableList", tableList);
		     resultMap.put("fieldList", apiOfTableOfFieldList);
		     resultMap.put("apiRequestParamList", apiRequestParamList);
		     resultMap.put("apiResponseParamList", apiResponseParamList);
		     resultMap.put("updateFieldList", updateFieldList);
		     resultMap.put("addFieldList", addFieldList);
		     resultMap.put("apiVersionManage", apiVersionManage);
		     resultMap.put("fileApiCatalogList", fileApiCatalogList);
		     resultMap.put("fileApiNameList", fileApiNameList);
		 }
		return resultMap;
	}
	/**
	 * 
	 * @Description: 第三方地址的url 格式 http://localhost:8080/v1/apiManage/apiVersionDetails
	 * @param:map 拼接参数的占位符      
	 * @date:   2019年4月4日 下午3:24:31  
	 * @author: wangshunyi    
	 * @throws
	 */

	private static String getUrlStrParamsByMap(String url,Map<String, Object> map) {
        if (map.isEmpty()) {
            return url;
        }
        StringBuffer sb = new StringBuffer();
        sb.append(url).append("?");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=${" + entry.getKey()+"}");
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }

	
	public PageInfo selectVerifyPassApiManagePageBySearchParams(Integer pageNum, Integer pageSize, String name,
			String apiTypeId,String apiType) {
		PageHelper.startPage(pageNum, pageSize);
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("name", name);
		paramMap.put("apiTypeId", apiTypeId);
		paramMap.put("apiType", apiType);
		List<ApiManage> verifyPassApiManageList = apiManageMapper.selectVerifyPassApiManagePageBySearchParams(paramMap);
		if(verifyPassApiManageList!=null&&verifyPassApiManageList.size()>0) {
			for (ApiManage apiManage : verifyPassApiManageList) {
				String url = apiManage.getUrl();
				String zsetMember = url.replaceFirst("\\/", "").replace("/", ":");
				double zscore = CacheZSet.zscore(PER_API_VISITCOUNT, zsetMember);
				//log.info("=================="+zscore);
				if(zscore==-1.0) {
					apiManage.setUseTimes(0.0);
				}else {
					apiManage.setUseTimes(zscore);
				}
			}
		}
		PageInfo page=new PageInfo(verifyPassApiManageList);
		return page;
	}
	public PageInfo selectVerifyApiManagePageBySearchParams(Integer pageNum, Integer pageSize, String applyName,
			String verifyStatus, String changeType, String apiName) {
		PageHelper.startPage(pageNum, pageSize);
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("applyName", applyName);
		paramMap.put("verifyStatus", verifyStatus);
		paramMap.put("changeType", changeType);
		paramMap.put("apiName", apiName);
		List<ApiManage> erifyApiManageList = apiManageMapper.selectVerifyApiManagePageBySearchParams(paramMap);
		PageInfo page=new PageInfo(erifyApiManageList);
		return page;
	}
	private void deleteApiVersionAttachInfo(Integer apiVersionId) {
		List<ApiOfTable> existApiOfTableList = apiOfTableMapper.selectApiOfTableByApiVersionId(apiVersionId);
		for (ApiOfTable apiOfTable : existApiOfTableList) {
			apiOfTableMapper.delete(apiOfTable);
			
		}
		List<ApiOfTableOfField> existApiOfTableOfFieldList = apiOfTableOfFieldMapper.selectApiOfTableOfFieldListByApiVersionId(apiVersionId);
		for (ApiOfTableOfField apiOfTableOfField : existApiOfTableOfFieldList) {
			apiOfTableOfFieldMapper.delete(apiOfTableOfField);
			
		}
		List<ApiRequestParam> existApiRequestParam = apiRequestParamMapper.selectApiRequestParamListByApiVersionId(apiVersionId);
		for (ApiRequestParam apiRequestParam : existApiRequestParam) {
			apiRequestParamMapper.delete(apiRequestParam);
			
		}
		List<ApiResponseParam> existApiResponseParamList = apiResponseParamMapper.selectApiResponseParamListByApiVersionId(apiVersionId);
		for (ApiResponseParam apiResponseParam : existApiResponseParamList) {
			apiResponseParamMapper.delete(apiResponseParam);
			
		}
		List<UpdateField> exitUpdateFieldList = updateFieldMapper.selectUpdateFieldListByApiVersionId(apiVersionId);
		for (UpdateField updateField : exitUpdateFieldList) {
			updateFieldMapper.delete(updateField);
			
		}
		List<AddField> selectAddFieldListByApiVersionId = addFieldMapper.selectAddFieldListByApiVersionId(apiVersionId);
		for (AddField addField : selectAddFieldListByApiVersionId) {
			addFieldMapper.delete(addField);
		}
		List<FileApiCatalog> selectFileApiCatalogByApiVersionId = fileApiCatalogMapper.selectFileApiCatalogByApiVersionId(apiVersionId);
		for (FileApiCatalog fileApiCatalog : selectFileApiCatalogByApiVersionId) {
			fileApiCatalogMapper.delete(fileApiCatalog);
			
		}
		List<FileApiName> selectFileApiNameByApiVersionId = fileApiNameMapper.selectFileApiNameByApiVersionId(apiVersionId);
		for (FileApiName fileApiName : selectFileApiNameByApiVersionId) {
			fileApiNameMapper.delete(fileApiName);
			
		}
	}
	/**
	 * @throws Exception 
	 * 
	 * @Description:对接口的禁用或者启用操作，注意：对接口的禁用操作的话会对接口下面的所有版本进行禁用操作 
	 * @date:   2019年3月29日 上午10:53:36  
	 * @author: wangshunyi    
	 * @throws
	 */
	@Transactional(rollbackFor=Exception.class)
	public void enableOrDisableOperation(Integer apiId, String status) throws Exception {
		ApiManage apiManage = apiManageMapper.selectByPrimaryKey(apiId);
		apiManage.setApiStatus(status);
		apiManageMapper.updateByPrimaryKeySelective(apiManage);
		//如果接口的状态是禁用操作，对应接口版本的状态也应该也是禁用
		if(status.equals(ApiStatusEnum.DISABLE.getStatus())) {
		 String cacheKey=(apiManage.getRequestMethod().toLowerCase()+apiManage.getUrl()).replace("/", ":");
			if(CacheExsite.isExsite(cacheKey)) {
				//缓存中存在，当禁用接口的时候需要删除key
				CacheCom.del(cacheKey);
			}
			/*List<ApiVersionManage> apiVersionManageList = apiVersionManageMapper.selectApiVersionManageListByApiId(apiId);
			for (ApiVersionManage apiVersionManage : apiVersionManageList) {
				apiVersionManage.setApiVersionStatus(ApiStatusEnum.DISABLE.getStatus());
				apiVersionManageMapper.updateByPrimaryKeySelective(apiVersionManage);
				
			}*/
			
		}
		
	}
	public Map<String, Object> getApiVersiondetails(Integer apiId) {
		ApiManage apiManage = apiManageMapper.selectApiManageByPrimaryKey(apiId);
		List<ApiVersionManage> apiVersionManageList = apiVersionManageMapper.selectApiVersionManageListByApiId(apiId);
		List<Apply> applyList = apiManageMapper.selectApplyListByApiId(apiId);
		Map<String,Object> resultMap=new HashMap<String,Object>();
		resultMap.put("apiBasicInfo", apiManage);
		resultMap.put("apiVersionManageList", apiVersionManageList);
		resultMap.put("applyList", applyList);
		return resultMap;
	}
	public ApiManage selectApiManageByPrimaryKey(Integer apiId) {
		return apiManageMapper.selectApiManageByPrimaryKey(apiId);
	}
	public boolean validateApiUrl(String url) {
		ApiManage validateApiUrl = apiManageMapper.validateApiUrl(url);
		if(validateApiUrl==null) {
			return false;
		}
		return true;
	}
	public void saveApiManageOutsideUrl(ApiManagerOutsideUrlParams apiManagerOutsideUrlParams) throws ApiManageIsNullExceptiuon, ApiManageSaveExceptiuon, ApiVersionManageIsNullExceptiuon, ApiVersionManageaveExceptiuon, ApplyIdIsNullExceptiuon {
		final String versionNumber="v1.00";
		String pageUrl=apiManagerOutsideUrlParams.getApiManage().getUrl();
		log.info(">>>保存开始页面传送的url="+pageUrl);
		ApiManage apiManage = apiManagerOutsideUrlParams.getApiManage();
		ApiVersionManage apiVersionManage = apiManagerOutsideUrlParams.getApiVersionManage();
		if(apiManage==null) {
			throw new ApiManageIsNullExceptiuon("接口基本信息不能为空");
		}
		//解析三方接口的url 2020-03-10
		String url = getUrl(apiManage.getUrl());
		apiManage.setUrl(API_PREFIX+url);
		log.info(">>>解析出来的url="+url);
		apiManage.setCreateTime(new Date());
		apiManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
		apiManage.setApiStatus(ApiStatusEnum.ENABLE.getStatus());
		apiManageMapper.saveApiManage(apiManage);
		if(log.isDebugEnabled()) {
			log.debug("apiManage save success after id="+apiManage.getId());
		}
		//保存成功以后返回接口的Id
		if(apiManage.getId()==null) {
			throw new ApiManageSaveExceptiuon("接口基本信息保存异常");
			
		}
		if(apiVersionManage==null) {
			throw new ApiVersionManageIsNullExceptiuon("接口版本不能为空");
			
		}
		//保存接口版本信息
		apiVersionManage.setApiId(apiManage.getId());
		apiVersionManage.setVersionNumber(versionNumber);
		apiVersionManage.setCreateTime(new Date());
		//管理员自己创建的接口默认是审核通过
		apiVersionManage.setApiVerifyStatus(ApiVerifyStatusEnum.VERIFY_PASS.getStatus());
		//审核人就是创建人
		apiVersionManage.setVerifyBy(apiVersionManage.getCreateBy());
		//审核时间就是创建时间
		apiVersionManage.setVerifyTime(new Date());
		//删除状态 正常
		apiVersionManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
		//接口版本是可用
		apiVersionManage.setApiVersionStatus(ApiStatusEnum.ENABLE.getStatus());
		//修改方式是添加
		apiVersionManage.setChangeType(ChangeTypeEnum.ADD.getStatus());
		apiVersionManageMapper.saveApiVersionManage(apiVersionManage);
		if(log.isDebugEnabled()) {
			log.debug("apiVersionManage save success after id="+apiVersionManage.getId());
		}
		if(apiVersionManage.getId()==null) {
			throw new ApiVersionManageaveExceptiuon("接口版本保存异常");
		}
		log.info(">>>页面传送的url="+pageUrl);
		List<Map<String, String>> urlRequestParams = getURLRequestParams(pageUrl);
		List<ApiRequestParam> apiRequestParams=new ArrayList<ApiRequestParam>();
		if(CollectionUtils.isNotEmpty(urlRequestParams)) {
			for (Map<String, String> map : urlRequestParams) {
				ApiRequestParam apiRequestParam=new ApiRequestParam();
				Set<String> keys = map.keySet();
				for (String key : keys) {
					//String name = map.get(key);
					apiRequestParam.setName(key);
					apiRequestParam.setPenName(key);
					apiRequestParam.setType("String");
					apiRequestParam.setIsRequired(YesOrNoStatusEnum.YES.getStatus());
					apiRequestParam.setApiVersionId(apiVersionManage.getId());
					apiRequestParams.add(apiRequestParam);
				}
				
			}
			apiRequestParamMapper.insertList(apiRequestParams);
		}
		if(apiManage.getApiType().equals(BUSINESS)) {
			List<ApplyApi> applyApiList=new ArrayList<ApplyApi>();
			ApplyApi applyApi=new ApplyApi();
			applyApi.setApiId(apiManage.getId());
			if(apiManage.getApplyId()==null) {
				throw new ApplyIdIsNullExceptiuon("接口管理==》business==》应用目录分类==》具体应用的applyId不能为null");
				
			}
			//关联具体的应用
			applyApi.setApplyId(apiManage.getApplyId());
			applyApi.setApiVersion(versionNumber);
			applyApi.setCreatedBy(apiVersionManage.getCreateBy());
			applyApiList.add(applyApi);
			applyManageMapper.saveApplyApi(applyApiList);
		}
	}
	public void updateApiManageOutsideUrl(ApiManagerOutsideUrlParams apiManagerOutsideUrlParams) throws Exception {
		ApiManage apiManage = apiManagerOutsideUrlParams.getApiManage();
		String pageUrl=apiManagerOutsideUrlParams.getApiManage().getUrl();
		log.info(">>>更新开始页面传送的url="+pageUrl);
		//解析三方接口的url 2020-03-10
		String url = getUrl(apiManage.getUrl());
		apiManage.setUrl(API_PREFIX+url);
		log.info(">>>解析出来的url="+url);
		ApiVersionManage apiVersionManage = apiManagerOutsideUrlParams.getApiVersionManage();
		if(apiVersionManage.getId()==null) {
			throw new ApiVersionManageaveExceptiuon("接口版本的id不能为空");
		}
		ApiVersionManage existApiVersionManage = apiVersionManageMapper.selectByPrimaryKey(apiVersionManage.getId());
		if(existApiVersionManage.getApiVerifyStatus().equals(ApiVerifyStatusEnum.VERIFY_PASS.getStatus())) {
			//审核通过的修改需要做版本的增加
			//更新接口基本信息
			apiManage.setId(existApiVersionManage.getApiId());
			
			
			apiManageMapper.updateByPrimaryKeySelective(apiManage);
			List<ApiVersionManage> apiVersionList = apiVersionManageMapper.selectApiVersionManageListByApiId(apiManage.getId());
			if(apiVersionList!=null) {
				for (ApiVersionManage avm : apiVersionList) {
					avm.setApiVersionStatus(ApiStatusEnum.DISABLE.getStatus());
					apiVersionManageMapper.updateByPrimaryKeySelective(avm);
				}
			}
			//接口版本以后的信息完全相当于新增
			//保存接口版本信息
			apiVersionManage.setId(null);
			apiVersionManage.setApiId(apiManage.getId());
			//拼接版本号
			double maxVersionNumber = getMaxVersionNumber(apiVersionList);
			double newVersion=maxVersionNumber+0.01;
			DecimalFormat df = new DecimalFormat("#.00");
			apiVersionManage.setVersionNumber("v"+df.format(newVersion));
			apiVersionManage.setCreateTime(new Date());
			//待审核状态 审核通过
			apiVersionManage.setApiVerifyStatus(ApiVerifyStatusEnum.VERIFY_PASS.getStatus());
			//删除状态 正常
			apiVersionManage.setDeleteStatus(DeleteStatusEnum.NORMAL.getStatus());
			//接口版本是启用
			apiVersionManage.setApiVersionStatus(ApiStatusEnum.ENABLE.getStatus());
			//修改方式是更新
			apiVersionManage.setChangeType(ChangeTypeEnum.UPDATE.getStatus());
			
			apiVersionManageMapper.saveApiVersionManage(apiVersionManage);
			if(log.isInfoEnabled()) {
				log.info("apiVersionManage save success after id="+apiVersionManage.getId());
			}
			String cacheKey=(apiManage.getRequestMethod().toLowerCase()+apiManage.getUrl()).replace("/", ":");
			if(CacheExsite.isExsite(cacheKey)) {
				//缓存中存在，需要删除key,因为访问接口的时候，执行的sql语句是从缓存中取出的
				CacheCom.del(cacheKey);
			}
			/*List<ApiRequestParam> apiRequestParamsa = apiRequestParamMapper.selectApiRequestParamListByApiVersionId(apiManagerOutsideUrlParams.getApiVersionManage().getId());
			if(CollectionUtils.isNotEmpty(apiRequestParamsa)) {
				for (ApiRequestParam apiRequestParam : apiRequestParamsa) {
					apiRequestParamMapper.delete(apiRequestParam);
				}
			}*/
			List<Map<String, String>> urlRequestParams = getURLRequestParams(pageUrl);
			log.info(">>>更新操作页面url="+pageUrl);
			List<ApiRequestParam> apiRequestParams=new ArrayList<ApiRequestParam>();
			if(CollectionUtils.isNotEmpty(urlRequestParams)) {
				for (Map<String, String> map : urlRequestParams) {
					ApiRequestParam apiRequestParam=new ApiRequestParam();
					Set<String> keys = map.keySet();
					for (String key : keys) {
						//String name = map.get(key);
						apiRequestParam.setName(key);
						apiRequestParam.setPenName(key);
						apiRequestParam.setType("String");
						apiRequestParam.setIsRequired(YesOrNoStatusEnum.YES.getStatus());
						apiRequestParam.setApiVersionId(apiVersionManage.getId());
						apiRequestParams.add(apiRequestParam);
					}
					
				}
				apiRequestParamMapper.insertList(apiRequestParams);
			}
			
		 }else {
			//别的状态下修改就不需要版本的叠加
			//更新接口基本信息
			apiManage.setId(existApiVersionManage.getApiId());
			apiManageMapper.updateByPrimaryKeySelective(apiManage);
			//更新接口版本的信息
			apiVersionManage.setChangeType(ChangeTypeEnum.UPDATE.getStatus());
			apiVersionManageMapper.updateByPrimaryKeySelective(apiVersionManage);
			
			List<ApiRequestParam> apiRequestParamsa = apiRequestParamMapper.selectApiRequestParamListByApiVersionId(apiManagerOutsideUrlParams.getApiVersionManage().getId());
			if(CollectionUtils.isNotEmpty(apiRequestParamsa)) {
				for (ApiRequestParam apiRequestParam : apiRequestParamsa) {
					apiRequestParamMapper.delete(apiRequestParam);
				}
			}
			List<Map<String, String>> urlRequestParams = getURLRequestParams(pageUrl);
			List<ApiRequestParam> apiRequestParams=new ArrayList<ApiRequestParam>();
			if(CollectionUtils.isNotEmpty(urlRequestParams)) {
				for (Map<String, String> map : urlRequestParams) {
					ApiRequestParam apiRequestParam=new ApiRequestParam();
					Set<String> keys = map.keySet();
					for (String key : keys) {
						String name = map.get(key);
						apiRequestParam.setName(name);
						apiRequestParam.setPenName(name);
						apiRequestParam.setType("String");
						apiRequestParam.setIsRequired(YesOrNoStatusEnum.YES.getStatus());
						apiRequestParam.setApiVersionId(apiVersionManage.getId());
						apiRequestParams.add(apiRequestParam);
					}
					
				}
				apiRequestParamMapper.insertList(apiRequestParams);
			}
			
		}
	}
	private  boolean isApiRequestParamDuplicatePenName(List<ApiRequestParam> apiRequestParamList) {
		List<String> exitPenNames=new ArrayList<String>();
		Set<String>  distinctPenNames=new HashSet<String>();
		for (ApiRequestParam apiRequestParam : apiRequestParamList) {
			exitPenNames.add(apiRequestParam.getPenName());
			distinctPenNames.add(apiRequestParam.getPenName());
		}
		if(exitPenNames.size()!=distinctPenNames.size()) {
			return true;
		}else {
			return false;
		}
	}
	private  boolean isApiResponseParamDuplicatePenName(List<ApiResponseParam> apiResponseParamList) {
		List<String> exitPenNames=new ArrayList<String>();
		Set<String>  distinctPenNames=new HashSet<String>();
		for (ApiResponseParam apiResponseParam : apiResponseParamList) {
			exitPenNames.add(apiResponseParam.getPenName().toLowerCase());
			distinctPenNames.add(apiResponseParam.getPenName().toLowerCase());
		}
		if(exitPenNames.size()!=distinctPenNames.size()) {
			return true;
		}else {
			return false;
		}
	}
	private  boolean isAddFieldDuplicatePenName(List<AddField> addFieldList) {
		List<String> exitPenNames=new ArrayList<String>();
		Set<String>  distinctPenNames=new HashSet<String>();
		for (AddField addField : addFieldList) {
			exitPenNames.add(addField.getPenName());
			distinctPenNames.add(addField.getPenName());
		}
		if(exitPenNames.size()!=distinctPenNames.size()) {
			return true;
		}else {
			return false;
		}
	}
	private  boolean isUpdateFieldDuplicatePenName(List<UpdateField> updateFieldList) {
		List<String> exitPenNames=new ArrayList<String>();
		Set<String>  distinctPenNames=new HashSet<String>();
		for (UpdateField updateField : updateFieldList) {
			exitPenNames.add(updateField.getPenName());
			distinctPenNames.add(updateField.getPenName());
		}
		if(exitPenNames.size()!=distinctPenNames.size()) {
			return true;
		}else {
			return false;
		}
	}
	public PageInfo selectChangeRecordByApiId(Integer  pageNum,Integer pageSize,Integer apiId,String verifyStatus,String changeType) {
		PageHelper.startPage(pageNum, pageSize);
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("apiId", apiId);
		paramMap.put("verifyStatus", verifyStatus);
		paramMap.put("changeType", changeType);
		List<ApiVersionManage> apiVersionManageList = apiVersionManageMapper.selectChangeRecordByApiId(paramMap);
		PageInfo page=new PageInfo<>(apiVersionManageList);
		return page;
		
		
	}
	public void deleteApply(Integer apiVersionId) {
		ApiVersionManage apiVersionManage = apiVersionManageMapper.selectByPrimaryKey(apiVersionId);
		apiVersionManage.setApiVerifyStatus(ApiVerifyStatusEnum.WAIT_VERIFY.getStatus());
		apiVersionManage.setUpdateTime(new Date());
		apiVersionManage.setChangeType(ChangeTypeEnum.DELETE.getStatus());
		apiVersionManageMapper.updateByPrimaryKeySelective(apiVersionManage);
		
	}
	public PageInfo selectDataApiShowList(Integer pageNum, Integer pageSize, Integer apiTypeId, String useOrder,
			String updateTimeOrder) {
		PageHelper.startPage(pageNum, pageSize);
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("useOrder",useOrder);
		paramMap.put("updateTimeOrder",updateTimeOrder);
		paramMap.put("apiTypeId", apiTypeId);
		List<ApiVersionManage> apiVersionManageList = apiManageMapper.selectDataApiShowList(paramMap);
		PageInfo page=new PageInfo<>(apiVersionManageList);
		return page;
	}
	private double getMaxVersionNumber(List<ApiVersionManage> apiVersionManageList) {
		DecimalFormat df = new DecimalFormat("#.00");
		List<String> versionStr= new ArrayList<String>();
		for (ApiVersionManage apiVersionManage : apiVersionManageList) {
			versionStr.add(apiVersionManage.getVersionNumber());
		}
		List<Double> maxData=new ArrayList<>();
		for (String string : versionStr) {
			double parseDouble = Double.parseDouble(string.replace("v", ""));
			maxData.add(parseDouble);
			
		}
		Collections.sort(maxData);
		return maxData.get(maxData.size()-1);
	}
	private  Set<String> getWhereNameBySql(String query) {
		Set<String> nameList=new HashSet<String>();
		int length = query.length();
		for (int i = 0; i < length; i++) {
			char c = query.charAt(i);
				 if (c == ':' && i + 1 < length && Character.isJavaIdentifierStart(query.charAt(i + 1))) {
					int j = i + 2;
					while (j < length && Character.isJavaIdentifierPart(query.charAt(j))) {
						j++;
					}
					String name = query.substring(i + 1, j);
					nameList.add(name);
				}
		}
		return nameList;
	}
	/**
	 * 
	 * @Description:根据sql语句解析出查询字段的笔名 
	 * @param: 用户输入的sql语句     
	 * @date:   2019年4月25日 下午4:32:09  
	 * @author: wangshunyi    
	 * @throws
	 */
	private  Set<String> getResponseParamBySql(String sql) {
		/*String str[] = sql.split(" ");
		List<String> responseName = new ArrayList<String>();
		List<String> resultName = new ArrayList<String>();
		for (int i = 0; i < str.length; i++) {
			if ("as".equalsIgnoreCase(str[i])) {
				responseName.add(str[i + 1]);
			}
		}
		for (int j = 0; j < responseName.size(); j++) {
			if (responseName.get(j).contains(",")) {
				String[] split = responseName.get(j).split(",");
				resultName.add(split[0]);
			} else {
				resultName.add(responseName.get(j));
			}
		}
		return resultName;*/
		Set<String> resultList=new HashSet<String>();
	    String column = sql.toLowerCase().split("from")[0].trim();
	    String[] columns = column.split(",");
	    for(String str : columns){
	        str = str.trim().replaceAll("select\\s+","");
	        str = str.replaceAll("`","");
	        if(str.indexOf("(")>=0 && str.indexOf(")")==-1) {
	        	continue;
	        }else if(str.indexOf("as")>=0 || str.indexOf("AS")>=0) {
	        	String[] asStr = str.split(" ");
	        	for (int i = 0; i < asStr.length; i++) {
					if ("as".equalsIgnoreCase(asStr[i])) {
						resultList.add(asStr[i + 1]);
					}
				}
	        //}
	        //else if(str.indexOf("as")>=0){
	           //str = str.replaceAll("^([^s]*)as\\s+","");
	          // resultList.add(str);
	        }else if(str.indexOf(" ")>=0){
	           str = str.replaceAll("^([^s]*)\\s+","");
	           resultList.add(str);
	        }else if(str.indexOf(".")>=0){
	            str = str.replaceAll("^([^s]*)\\.","");
	            resultList.add(str);
	        }else {
	        	resultList.add(str);
	        }
	    }
	    return resultList;
	}

	@Override
	public List<Map<String,Object>> findAllApi() {
		return apiManageMapper.findAllApplyAndApi();
	}
	@Override
	public ApiManage selectApiManageByUrl(String url) {
		return apiManageMapper.selectApiManageByUrl(url);
	}
	@Override
	public ApiManage selectApiManageAndApiversionByUrlAndEnable(String requestURI) {
		return apiManageMapper.selectApiManageAndApiversionByUrlAndEnable(requestURI);
	}
	@Override
	public Map<String, Object> apiTotal() {
		return apiManageMapper.apiTotal();
	}

	@Override
	public PageInfo getApiByTableId(Integer pageNum, Integer pageSize, Integer tableId) {
		PageHelper.startPage(pageNum, pageSize);
		List<ApiManage> apiManages = apiManageMapper.getApiByTableId(tableId);
		PageInfo page=new PageInfo<>(apiManages);
		return page;
	}

	@Override
	public Integer selectDataApiShowListCount(Integer apiTypeId) {
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("apiTypeId", apiTypeId);
		return  apiManageMapper.selectDataApiShowListCount(paramMap);
	}

	/**
	 * 
	 * @Description: 判断两个list中是否有重复的元素 
	 * @date:   2019年7月24日 下午5:17:26  
	 * @author: wangshunyi    
	 * @throws
	 */
	public  boolean isListElementDuplicat(List<String> list1,List<String> list2) {
		Set<String> set=new HashSet<String>(list1);
		set.addAll(list2);
		if(list1.size()+list2.size()!=set.size()) {
			return false;
		}
		return true;
	}
	/**
	 * 
	 * @Description: 提取url中的请求参数  
	 * @date:   2019年7月26日 上午9:59:22  
	 * @author: wangshunyi    
	 * @throws
	 */
	private  List<String> getNameByUrl(String query) {
		List<String> nameList=new ArrayList<String>();
		int length = query.length();
		for (int i = 0; i < length; i++) {
			char c = query.charAt(i);
				 if (c == '{' && i + 1 < length && Character.isJavaIdentifierStart(query.charAt(i + 1))) {
					int j = i + 2;
					while (j < length && Character.isJavaIdentifierPart(query.charAt(j))) {
						j++;
					}
					String name = query.substring(i + 1, j);
					nameList.add(name);
				}
		}
		return nameList;
	}
	/**
	 * 
	 * @Description:判断一个List中是否有重复的元素 
	 * @param:    list1  
	 * @return:   boolean
	 * @date:   2019年7月26日 上午10:08:55  
	 * @author: wangshunyi    
	 * @throws
	 */
	public  boolean isListDuplicat(List<String> list1) {
		Set<String> tempSet=new HashSet<String>(list1);
		if(list1.size()==tempSet.size()) {
			return true;
		}
		return false;
	}
	@Override
	public PageInfo searchApiListByName(Integer pageNum, Integer pageSize, String name) {
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("name", name);
		PageHelper.startPage(pageNum, pageSize);
		List<ApiManage> apiManages = apiManageMapper.searchApiListByName(paramMap);
		PageInfo page=new PageInfo<>(apiManages);
		return page;
	}

	@Override
	public List<Map<String, String>> getAppKeyApiUrls() {
		return apiManageMapper.getAppKeyApiUrls();
	}

	@Override
	public List<ApiManage> getApiInfoByIds(String[] apiId) {
		return apiManageMapper.getApiInfoByIds(apiId);
	}

	@Override
	public PageInfo getApiVersionByTableId(Integer pageNum, Integer pageSize, Integer tableId) {
		PageHelper.startPage(pageNum, pageSize);
		List<Map<String,Object>> apiVersions = apiManageMapper.getApiVersionByTableId(tableId);
		PageInfo page=new PageInfo<>(apiVersions);
		return page;
	}

	/**
	 * 解析出url参数中的键值对 存入map中
	 * 
	 * @param url
	 *            url地址
	 * @return url请求参数部分
	 */
	public List<Map<String, String>> getURLRequestParams(String url) {
		List<Map<String, String>> params=new ArrayList<Map<String,String>>();
		String[] arrSplit = null;
		String strUrlParam = truncateUrl(url);
		if (strUrlParam == null) {
			return params;
		}
		arrSplit = strUrlParam.split("[&]");
		for (String strSplit : arrSplit) {
			Map<String, String> mapRequest = new HashMap<String, String>();
			String[] arrSplitEqual = null;
			arrSplitEqual = strSplit.split("[=]");
			// 解析出键值
			if (arrSplitEqual.length >1) {
				// 正确解析
				mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
				params.add(mapRequest);

			} else {
				if (arrSplitEqual[0] != "") {
					// 只有参数没有值，不加入
					mapRequest.put(arrSplitEqual[0], "");
					params.add(mapRequest);
				}
			}
		}
		return params;
	}

	/**
	 * 去掉url中的路径，留下请求参数部分
	 * 
	 * @param strURL
	 *            url地址
	 * @return url请求参数部分
	 */
	private  String truncateUrl(String strURL) {
		String strAllParam = null;
		String[] arrSplit = null;

		strURL = strURL.trim().toLowerCase();

		arrSplit = strURL.split("[?]");
		if (strURL.length() > 1) {
			if (arrSplit.length > 1) {
				if (arrSplit[1] != null) {
					strAllParam = arrSplit[1];
				}
			}
		}

		return strAllParam;
	}

	/**
	 * 解析出url请求的路径，包括页面
	 * 
	 * @param strURL
	 *            url地址
	 * @return url路径
	 */
	public String getUrl(String strURL) {
		String strPage = null;
		String[] arrSplit = null;
		strURL = strURL.trim();
		if(strURL.indexOf("?")==-1) {
			return strURL;
		}
		arrSplit = strURL.split("[?]");
		if (strURL.length() > 0) {
			if (arrSplit.length > 1) {
				if (arrSplit[0] != null) {
					strPage = arrSplit[0];
				}
			}
		}
		return strPage;
	}

}
